package com.jinlejia.feedback.question.ui;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.SimpleItemAnimator;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioGroup;

import com.dialog.JLJCommonDialog;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.common.weight.JLJProgressDialog;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.databinding.CommonEvent;
import com.jinlejia.feedback.databinding.FbActivityQuestionDetailsBinding;
import com.jinlejia.feedback.question.adapter.question.KeyHelper;
import com.jinlejia.feedback.question.adapter.question.QuestionDetailsAdapter;
import com.jinlejia.feedback.question.http.QuestionDetailsHelper;
import com.utils.SoftKeyBoardEvent;
import com.weight.CustomToast;

import java.util.ArrayList;
import java.util.Map;


//问题详情
public class FbQuestionDetailsActivity extends AppCompatActivity implements YfLoadMoreListener, KeyHelper.EventListener {

    private FbActivityQuestionDetailsBinding binding;
    private QuestionDetailsHelper helper;

    private String problemCode; //问题编码 from Intent
    private String showButton; //按钮状态 from Http
    private String solutionCode; //解决方案编码 from Http

    private int satisfaction = -1; //评价满意度 from binding.iconRadioGroup
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.fb_activity_question_details);
        binding.setCommonEvent(CommonEvent.obtain());
        binding.setEvent(this);
        helper = new QuestionDetailsHelper(binding);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras!=null)
            problemCode = extras.getString("problemCode", problemCode);
        initView();
    }

    private QuestionDetailsAdapter adapter;
    private void initView(){
        binding.emptyLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SoftKeyBoardEvent.hideSoftInput(FbQuestionDetailsActivity.this);
                return true;
            }
        });
        SoftKeyBoardEvent.setListener(this, new SoftKeyBoardEvent.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                binding.emptyLayout.setVisibility(View.VISIBLE);
                binding.submitInfoButton.setVisibility(View.GONE);
                binding.submitAnnounceInfoButton.setVisibility(View.VISIBLE);
            }

            @Override
            public void keyBoardHide(int height) {
                binding.emptyLayout.setVisibility(View.GONE);
                if (!"0".equals(showButton)){ //如果按钮状态不是不显示
                    binding.submitInfoButton.setVisibility(View.VISIBLE);
                }
                binding.inputEditText.setHint("输入内容");
                binding.inputEditText.setTag(problemCode);
                binding.submitAnnounceInfoButton.setVisibility(View.GONE);
            }
        });
        binding.inputEditText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (binding.submitAnnounceInfoButton.getVisibility()!=View.VISIBLE){ //键盘显示
                    binding.inputEditText.setHint("输入内容");
                    binding.inputEditText.setTag(problemCode);
                }
                return false;
            }
        });
        binding.inputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()){
                    binding.submitAnnounceInfoButton.setEnabled(false);
                }else {
                    binding.submitAnnounceInfoButton.setEnabled(true);
                }
            }
        });
        binding.iconRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                binding.selectTextInfo1.setText(null);
                binding.selectTextInfo2.setText(null);
                binding.selectTextInfo3.setText(null);
                binding.selectTextInfo4.setText(null);
                binding.selectTextInfo5.setText(null);
                if (checkedId == R.id.veryBadRadioButton) {
                    satisfaction = 0;
                    binding.selectTextInfo1.setText("非常不满意");

                } else if (checkedId == R.id.badRadioButton) {
                    satisfaction = 1;
                    binding.selectTextInfo2.setText("不满意");

                } else if (checkedId == R.id.normalRadioButton) {
                    satisfaction = 2;
                    binding.selectTextInfo3.setText("一般");

                } else if (checkedId == R.id.okRadioButton) {
                    satisfaction = 3;
                    binding.selectTextInfo4.setText("满意");

                } else if (checkedId == R.id.veryOkRadioButton) {
                    satisfaction = 4;
                    binding.selectTextInfo5.setText("非常满意");

                }
            }
        });

        binding.yfListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.yfListRecyclerView.setHasFixedSize(true);
        ((SimpleItemAnimator)binding.yfListRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        ArrayList<Map<String, Object>> data = new ArrayList<>();
        adapter = new QuestionDetailsAdapter(data);
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.yfListRecyclerView.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);
        adapter.setEventListener(this);
        loadData();
    }

    private boolean mLoadingLock = false;
    private void loadData(){
        mLoadingLock = true;
       // problemCode = "PM1001";
        helper.getProblem(problemCode, new QuestionDetailsHelper.GetProblemCallBack() {
            @Override
            public void onResult(Map<String, Object> result, ArrayList<Map<String, Object>> data) {
                adapter.setDataList(data);
                adapter.changeMode(YfListMode.MODE_DATA);
                //解决方案编码
                solutionCode = String.valueOf(result.get("solutionCode"));
                //region 初始化按钮状态
                showButton = String.valueOf(result.get("showButton"));
                //一键总经理是否展示
                boolean isGeneral = (boolean) result.get("isGeneral");
                if (isGeneral){
                    binding.callGeneralTextView.setVisibility(View.GONE);
                }else {
                    binding.callGeneralTextView.setVisibility(View.VISIBLE);
                }
                showButtonByState();
                //endregion
                mLoadingLock = false;
            }

            @Override
            public void onEmpty() {
                adapter.changeMode(YfListMode.MODE_EMPTY);
                mLoadingLock = false;
                binding.bottomLayout.setVisibility(View.GONE);
            }

            @Override
            public void onError() {
                adapter.changeMode(YfListMode.MODE_ERROR);
                binding.bottomLayout.setVisibility(View.GONE);
                mLoadingLock = false;
            }
        });
    }

    private void showButtonByState(){
        if ("0".equals(showButton)){ //不显示
            binding.submitInfoButton.setVisibility(View.GONE);
        }else if ("1".equals(showButton)){ //确认方案
            binding.submitInfoButton.setEnabled(true);
            binding.submitInfoButton.setVisibility(View.VISIBLE);
            binding.submitInfoButton.setText("确认方案");
        }else if ("2".equals(showButton)){ //确认解决
            binding.submitInfoButton.setEnabled(true);
            binding.submitInfoButton.setVisibility(View.VISIBLE);
            binding.submitInfoButton.setText("确认解决");
        }else if ("3".equals(showButton)){ //评价
            binding.submitInfoButton.setEnabled(true);
            binding.submitInfoButton.setVisibility(View.VISIBLE);
            binding.submitInfoButton.setText("评价");
        }
    }

    //一键总经理
    public void callGeneral(View view){
        if (dialog!=null){
            dialog.dismiss();
            dialog = null;
        }
        dialog = new JLJCommonDialog(this,"确认","是否提交总经理");
        dialog.setConfirmListener(new JLJCommonDialog.OnConfirmListener() {
            @Override
            public void confirm() {
                showProgressDialog(null);
                helper.oneKeyGeneral(problemCode, new QuestionDetailsHelper.OneKeyGeneralCallBack() {
                    @Override
                    public void onResult(boolean flag, String message) {
                        if (flag){
                            CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                            binding.callGeneralTextView.setVisibility(View.GONE);
                        }else {
                            CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                        }
                        closeProgressDialog();
                    }
                });
            }
        });
        dialog.show();

    }

    //关闭评价对话框
    public void closeEvaluateLayout(View view){
        binding.evaluateLayout.setVisibility(View.GONE);
    }

    //提交评论
    public void submitEvaluate(View view){
        if (satisfaction==-1)return;
        showProgressDialog(null);
        String inputEvaluate = binding.inputEvaluateEditText.getText().toString();
        helper.addEvaluate(problemCode, satisfaction, inputEvaluate, new QuestionDetailsHelper.AddEvaluateCallBack() {
            @Override
            public void onResult(boolean result, String message,String buttonState) {
                if (result){
                    binding.inputEvaluateEditText.setText(null);
                    binding.selectTextInfo1.setText(null);
                    binding.selectTextInfo2.setText(null);
                    binding.selectTextInfo3.setText(null);
                    binding.selectTextInfo4.setText(null);
                    binding.selectTextInfo5.setText(null);
                    binding.iconRadioGroup.clearCheck();
                    binding.evaluateLayout.setVisibility(View.GONE);
                    binding.evaluateInputLayout.setVisibility(View.GONE);
                    binding.evaluateSuccessLayout.setVisibility(View.VISIBLE);
                    showButton = buttonState;
                    showButtonByState();
                }else
                    CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                closeProgressDialog();
            }
        });
    }


    //发表
    private String replyCode, toUserId, toUserName; //from KeyHelper.EventListener#onReplyComment
    public void submitAnnounceInfo(View view){
        String tag = (String) binding.inputEditText.getTag();
        String text = binding.inputEditText.getText().toString();
        if (TextUtils.equals(tag,problemCode)){ //提交回复
            showProgressDialog(null);
            helper.saveReply(problemCode, text, new QuestionDetailsHelper.SaveReplyCallBack() {
                @Override
                public void onResult(boolean flag, String message) {
                    if (flag){ //当发表成功后，刷新回复列表
                        pageIndex=1;
                        binding.inputEditText.setTag(null);
                        binding.inputEditText.setText(null);
                        SoftKeyBoardEvent.hideSoftInput(FbQuestionDetailsActivity.this);
                        CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                        searchReplyList();
                    }else
                        CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                    closeProgressDialog();
                }
            });
        }else {
            showProgressDialog(null);
            helper.saveReplyComment(problemCode, replyCode, toUserId, toUserName, text, new QuestionDetailsHelper.SaveReplyCommentCallBack() {
                @Override
                public void onResult(boolean flag, String message) {
                    if (flag){ //当发表成功后，刷新回复列表
                        binding.inputEditText.setText(null);
                        binding.inputEditText.setTag(null);
                        CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                        SoftKeyBoardEvent.hideSoftInput(FbQuestionDetailsActivity.this);
                        pageIndex=1;
                        searchReplyList();
                    }else
                        CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                    closeProgressDialog();
                }
            });
        }
    }

    private JLJCommonDialog dialog;
    //确认解决 or 确认方案
    public void submitInfo(View view){
        if (dialog!=null){
            dialog.dismiss();
            dialog = null;
        }
        if ("1".equals(showButton)){ //确认解决方案
            dialog = new JLJCommonDialog(this,"确认方案","确认接受解决方案？");
            dialog.setConfirmListener(new JLJCommonDialog.OnConfirmListener() {
                @Override
                public void confirm() {
                    confirmSolution();
                }
            });
            dialog.show();
        }else if ("2".equals(showButton)){ //问题确认解决
            dialog = new JLJCommonDialog(this,"确认解决","确认问题已解决？");
            dialog.setConfirmListener(new JLJCommonDialog.OnConfirmListener() {
                @Override
                public void confirm() {
                    confirmSettle();
                }
            });
            dialog.show();
        }else if ("3".equals(showButton)){ //评价
           binding.evaluateLayout.setVisibility(View.VISIBLE);
        }
    }

    //确认解决方案
    private void confirmSolution(){
        showProgressDialog(null);
        helper.confirmSolution(solutionCode, new QuestionDetailsHelper.ConfirmSolutionCallback() {
            @Override
            public void onResult(boolean result, String message,String buttonState) {
                if (result){
                    showButton = buttonState;
                    CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                    showButtonByState();
                }else {
                    CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                }
                //解决成功
                closeProgressDialog();
            }
        });
    }

    //问题确认解决
    private void confirmSettle(){
        showProgressDialog(null);
        helper.confirmSettle(problemCode, new QuestionDetailsHelper.ConfirmSettleCallback() {
            @Override
            public void onResult(boolean result, String message, String showButtonState) {
                if (result){
                    showButton = showButtonState;
                    showButtonByState();
                    binding.evaluateLayout.setVisibility(View.VISIBLE);
                }else {
                    CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                }
                closeProgressDialog();
            }
        });
    }

    //region 点击键盘外
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
//                v.clearFocus();
//                SoftKeyBoardEvent.hideSoftInput(this);
                super.dispatchTouchEvent(ev);
            }

        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = { 0, 0 };
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }
    //endregion

    private int pageIndex = 2; //默认查询第二页
    @Override
    public void loadMore() {
        adapter.addFooter("loading...");
        searchReplyList();
    }
    private void searchReplyList(){
        if (mLoadingLock){
            return;
        }
        mLoadingLock = true;
        @SuppressWarnings("unchecked")
        ArrayList<Map<String,Object>> tempData = new ArrayList<>(adapter.mData);
        helper.listReply(tempData, pageIndex, problemCode, new QuestionDetailsHelper.ListReplyCallBack() {
            @Override
            public void onResult(ArrayList<Map<String, Object>> result,int resultSize) {
                adapter.removeAllFooters();
                if (pageIndex==1){
                    adapter.setDataList(result);
                }else {
                    if (result!=null && result.size()>0){
                        adapter.addDataList(result);
                    }
                }
                pageIndex = pageIndex +1;
                mLoadingLock = false;
                closeProgressDialog();
            }

            @Override
            public void onNoMore() {
                adapter.removeAllFooters();
                adapter.addFooter("没有更多了");
                mLoadingLock = false;
                closeProgressDialog();
            }

            @Override
            public void onError() {
                adapter.removeAllFooters();
                CustomToast.showToast(FbQuestionDetailsActivity.this,"网络异常",1500);
                mLoadingLock = false;
                closeProgressDialog();
            }
        });
    }
    //region EventListener
    @Override
    public void onSearchReply() {
        showProgressDialog(null);
        pageIndex=1;
        searchReplyList();
    }

    @Override
    public void onLikeOperation(boolean currentState,String likeCode, QuestionDetailsHelper.LikeType likeType, final Map<String, Object> map,final int position) {
        helper.likeOperation(currentState,likeCode, likeType, new QuestionDetailsHelper.LikeOrCollectCallBack() {
            @Override
            public void onSuccess(QuestionDetailsHelper.LikeOrCollectType likeOrCollect, QuestionDetailsHelper.LikeType likeType, boolean state, int count) {
                if (likeOrCollect== QuestionDetailsHelper.LikeOrCollectType.Like){ //如果是点赞
                    if (likeType== QuestionDetailsHelper.LikeType.Question){ //如果是Question
                        boolean oldState = (boolean) map.get("likeState");
                        int oldCount = (int) map.get("likeCount");
                        if (oldState==state && oldCount==count){ //如果数据没有变化则，不进行重新绘画ITEM修改
                            adapter.notifyItemChanged(position);
                        }else {
                            map.put("likeState",state);
                            map.put("likeCount",count);
                        }
                    }else if (likeType == QuestionDetailsHelper.LikeType.Reply){ //如果是回复

                        boolean oldState = (boolean) map.get("replyLikeState");
                        int oldCount = (int) map.get("replyLikeCount");
                        if (oldState==state && oldCount==count){ //如果数据没有变化则，不进行重新绘画ITEM修改
                            adapter.notifyItemChanged(position);
                        }else {
                            map.put("replyLikeState",state);
                            map.put("replyLikeCount",count);
                        }
                    }
                }
            }

            @Override
            public void onFailed(String message) {
                CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
            }
        });
    }

    @Override
    public void onCollectOperation(final boolean currentState, String problemCode, QuestionDetailsHelper.LikeType likeType, final Map<String, Object> map, final int position) {
        showProgressDialog(null);
        helper.collectOperation(currentState,problemCode, likeType, new QuestionDetailsHelper.LikeOrCollectCallBack() {
            @Override
            public void onSuccess(QuestionDetailsHelper.LikeOrCollectType likeOrCollect, QuestionDetailsHelper.LikeType likeType, boolean state, int count) {
                closeProgressDialog();
                if (likeOrCollect== QuestionDetailsHelper.LikeOrCollectType.Collect){ //如果是收藏
                    if (likeType== QuestionDetailsHelper.LikeType.Question){ //如果是Question
                        map.put("collectState",state);
                        map.put("collectCount",count);
                        adapter.notifyItemChanged(position);
                    }

                    if (currentState){
                        CustomToast.showToast(FbQuestionDetailsActivity.this,"取消关注",1500);
                    }else{
                        CustomToast.showToast(FbQuestionDetailsActivity.this,"已关注",1500);
                    }
                }
            }

            @Override
            public void onFailed(String message) {
                CustomToast.showToast(FbQuestionDetailsActivity.this,message,1500);
                closeProgressDialog();
            }
        });
    }

    @Override
    public void onReplyComment(String replyCode, String toUserId, String toUserName,final int position) {
        this.replyCode = replyCode;
        this.toUserId = toUserId;
        this.toUserName = toUserName;
        binding.yfListRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.yfListRecyclerView.scrollToPosition(position);
            }
        },200);
        binding.inputEditText.setHint("回复："+toUserName); //显示回复某人
        binding.inputEditText.setTag(replyCode);
        binding.inputEditText.setFocusable(true);
        binding.inputEditText.setFocusableInTouchMode(true);
        binding.inputEditText.requestFocus();
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(binding.inputEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    @Override
    public void onToAllReplyActivity(String replyCode) {
        Intent intent = new Intent(FbQuestionDetailsActivity.this,FbRespondToDetailsActivity.class);
        intent.putExtra("replyCode",replyCode);
        intent.putExtra("problemCode",problemCode);
        startActivity(intent);
    }

    //endregion

    //region 加载框
    private JLJProgressDialog progressDialog;
    private void showProgressDialog(String tip){
        closeProgressDialog();
        progressDialog = new JLJProgressDialog(this,tip,false);
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if (progressDialog!=null){
            progressDialog.dismiss();
        }
        progressDialog = null;
    }
    //endregion
}
